param(
	#[string]$dmsWebUrl = "$(Read-Host 'Enter DMS Site Url [e.g. http://sites/dms]')",
	[string]$csvSource = "$(Read-Host 'Enter import csv file [e.g. c:\temp\source.csv]')",
	[string]$receiptSourceFolder ="$(Read-Host 'Enter receipt source folder')",
	#[string]$receiptRootWebUrl = "$(Read-Host 'Enter receipt web url [e.g. http://dms/sites/receipts]')",
	[string]$importYear =  "$(Read-Host 'Enter the receipt year [e.g. 2012]')"
)






#Load variables from configuration file
[System.Xml.XmlDocument] $xmlDoc = New-Object System.Xml.XmlDocument
$file = Resolve-Path (".\deployment.config")

if(!$file){
	Write-Host "Could not find the configuration file deployment.cnofig. Aborting." -ForegroundColor Red
	break
}

Write-Host "Parsing file: " $file
$xmlDoc = [xml](Get-Content $file)

$dmsWebUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.Url
$receiptRootWebUrl = $xmlDoc.Configuration.WebApplication.SiteCollection.ReceiptSite.Url

$searchService = $xmlDoc.Configuration.SearchService.Name
$scopeName =$xmlDoc.Configuration.SearchService.SearchScope.Name



		$spReceiptListName = "Receipts"
		$spReceiptDocumentLibraryName = "ReceiptDocuments"
		
		$documentType = "DocumentType"
		
		$receiptNumber = "Title"
		$customerName = "CustomerName"
		$firstName = "FirstName"
		$customerNumber = "CustomerNumber"	
		$totalAmount = "TotalAmount"
		$branchName = "BranchName" 
		$username = "Username"
		$invoiceNumber = "InvoiceNumber"
		$invoiceType = "InvoiceType"
		$amount = "Amount"
		$receiptType = "ReceiptType"
		$startTime = "StartTime"
		$bidderNo = "BidderNo"
		$histDocumentNo = "HistDocumentNo"
		$receiptDate = "ReceiptDate"

		#Year we are importing for
		
		if(!$receiptSourceFolder.EndsWith('\'))
		{
			$receiptSourceFolder = $receiptSourceFolder + '\'
		}
		
Add-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue		
		
Write-Host "`n===================`n# Starting Import #`n==================="


function getBranchNameID($branchName,$branchCode){
	#Write-Host "Get Branch ID" $branchName $branchCode 
	$web = Get-SPWeb -identity $dmsWebUrl
	$branchList = $web.Lists['Branches'];
	$branches = $branchList.Items
	$branchID = 0;
	foreach($item in $branches){
		if($item["Title"] -eq $branchName)
		{
			$branchID = $item.ID
		}
	}
	if($branchID -eq 0){
		Write-Host "branch $branchName, which code is $branchCode doesn't exist in the list, insert to the list" -ForegroundColor Yellow
		$item = $branchList.AddItem();
		$item["Title"] = $branchName;
		$item["BranchCode"] = $branchCode;
		$item.update();
		$branchID = $item.ID;
		
		$web.Dispose();
	}
	else{
		$web.Dispose();	
	}
	
	return $branchID;
}

function GetFolderFromMD5($fileName){
	$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
	$utf8 = New-Object -TypeName System.Text.UTF8Encoding
	$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($fileName)))
	return $hash.Substring(0,2)
}


#Load the CSV file
#$csvSource = 'D:\Document Types\Invoices containing multiple sales\2012-05-21-11-10-20.csv'
$csvLength = @(Get-Content $csvSource).Length
$csv = Import-Csv $csvSource
Write-Host "CSV file loaded"

#Store the source folder
#$invoiceSourceFolder = 'D:\Document Types\Invoices containing multiple sales\'
#Write-Host "Source folder loaded"


if(!$receiptRootWebUrl.EndsWith('/'))
{
	$receiptRootWebUrl = $receiptRootWebUrl + '/'
}

$receiptYearWebUrl = $receiptRootWebUrl + $importYear

#Load the site
$web = Get-SPWeb -identity $receiptYearWebUrl #"http://turnersdms/receipts/2011/"
Write-Host "Site" $receiptYearWebUrl " loaded"

$webRelativeUrl = $web.ServerRelativeUrl

#Load the document library
$listDocuments = $web.Lists[$spReceiptDocumentLibraryName]
if(!$listDocuments){Write-Host 'list document is null' -ForegroundColor Red
	exit
}else{
	Write-Host 'list document loaded'-ForegroundColor Green
}

$receiptList = $web.Lists[$spReceiptListName]
if(!$receiptList){Write-Host 'receipt list is null' -ForegroundColor Red 
	exit
}else{
	Write-Host 'receipt list is loaded'-ForegroundColor Green
}

#Create folder
#Write-host "Creating initial folder"
#$currentFolderDocuments = $listDocuments.RootFolder.Subfolders.Add("$folderCountDocuments")
#$currentFolderListItems = $listListItems.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
#$currentFolderListItems["Title"] = $folderCountListItems
#$currentFolderListItems.Update();
$itemCountDocuments = 0
$itemCountListItems = 0
foreach ($row in $csv){
	
	$receiptNumber = $row.ReceiptNumber
	Write-Host "Receipt Number: " $receiptNumber -ForegroundColor Yellow
	$docFolderName = GetFolderFromMD5 -fileName $receiptNumber
	
	
	#create folder $docFolderName is not exist
	
	$targetDocumentFolder = $web.GetFolder($listDocuments.RootFolder.ServerRelativeUrl + "/" + $docFolderName)
	#Write-Host $listDocuments.RootFolder.ServerRelativeUrl -ForegroundColor Yellow
	#Write-Host $docFolderName -ForegroundColor Yellow
	if(-not $targetDocumentFolder.Exists)
	{
		$targetDocumentFolder = $listDocuments.RootFolder.SubFolders.Add("$docFolderName")	
		#Write-Host $targetDocumentFolder.Url
		#Write-Host "target folder is created"
	}
	
	$targetListFolder = $web.GetFolder($receiptList.RootFolder.ServerRelativeUrl + "/" + $docFolderName)
	
	if(-not $targetListFolder.Exists){
		$targetListFolder = $receiptList.AddItem("",[Microsoft.SharePoint.SPFileSystemObjectType]::Folder)
		$targetListFolder["Title"] = $docFolderName
		$targetListFolder.Update();
		#Write-Host $targetListFolder.Url
		#Write-Host "target folder is created"
	}
	
	$fileName = $row.ReceiptNumber + ".pdf"
	$filePath = $receiptSourceFolder +  $fileName
	#make sure the pdf file exist before trying to upload to sharepoint
	if(Test-Path $filePath){
		#Write-Host "file name: " $fileName -ForegroundColor Green 
		#Write-Host "source folder path: " $receiptSourceFolder -ForegroundColor Green
		#Write-Host "file path: " $filePath -ForegroundColor Green
		# Check if file exists
		$filePathAtDestination = "$targetDocumentFolder/$fileName"
		$fileExists = $web.GetFile($filePathAtDestination).Exists
		#Write-Host "file path at destination: " $filePathAtDestination
		try
		{
			$fileStream = ([System.IO.FileInfo] (Get-Item $filePath)).OpenRead()
			
			# If file hasn't been added already, add it

			if(!$fileExists)
			{
				Write-Host "Adding file " $fileName
				$spFile = $targetDocumentFolder.Files.Add($targetDocumentFolder.Url + "/" + $fileName, [System.IO.Stream] $fileStream, $false)
				$itemCountDocuments++
			}		
		
			$itemFolderUrl = $targetListFolder.Url + "/"
			#Write-Host "item folder url " $itemFolderUrl 
			$item = $receiptList.AddItem($itemFolderUrl, [Microsoft.Sharepoint.SPFileSystemObjectType]::File, $row.ReceiptNumber)
			
			 $item["Title"] = $row.ReceiptNumber
			#Write-Host "CustomerName: "  $row.CoName
			$item["CustomerName"] = $row.CoName
			#Write-Host "TotalAmount: "  $row.TotalAmount
			$item["TotalAmount"] = $row.TotalAmount
			#Write-Host "Username: "  $row.FullName
			$item["Username"] = $row.FullName
			#Write-Host "InvoiceNumber: "  $row.InvoiceNumber
			$item["InvoiceNumber"] = $row.InvoiceNumber
			#Write-Host "InvoiceType: "  $row.InvoiceTypeCode
			$item["InvoiceType"] = $row.InvoiceTypeCode
			#Write-Host "Amount: "  $row.Amount
			$item["Amount"] = $row.Amount
			#Write-Host "ReceiptType: "  $row.ReceiptType
			$item["ReceiptType"] = $row.ReceiptType
			#Write-Host "StartTime: "  $row.StartTime
			if($row.StartTime.Length -ne 0)
			{
				$item["StartTime"] = $row.StartTime
			}
			#Write-Host "BidderNo: "  $row.BidderNo
			$item["BidderNo"] = $row.BidderNo
			#Write-Host "HistDocumentNo: "  $row.HistDocumentNo
			$item["HistDocumentNo"] = $row.HistDocumentNo
			#Write-Host "ReceiptDate: "  $row.ReceiptDate
			$item["ReceiptDate"] = $row.ReceiptDate 
			#Write-Host "CustomerNumber: "  $row.CustomerNo
			$item["CustomerNumber"] = $row.CustomerNo
			$item["FirstName"] = $row.FirstName
			
			$branchID = getBranchNameID -branchName $row.BranchName -branchCode $row.BranchCode
			#Write-Host "Branch ID is: " $branchID
			$item["BranchName"] = $branchID
			
			$documentUrl = New-Object Microsoft.SharePoint.SPFieldURLValue
			$documentUrl.Description = $fileName
			$webUrl = $web.Url
			$documentUrl.URL = "$webUrl/$targetDocumentFolder/$fileName"
			
			#Write-Host "documetnUrl:" $documentUrl.URL

			$item["DocumentLink"] = $documentUrl
			$itemCountListItems++
			$item.Update()
			
			
		
		}
		catch
		{
			Write-Host "Error adding file: " $filePath"`n"$_ -foregroundcolor red
			break
		}		
	}else{
		Write-Host "Missing file: " $filePath"`n"$_ -foregroundcolor red
	}
	
}

Write-Host "`n=================`nImport Completed.`nFiles Added: $itemCountDocuments.`nRows Added: $itemCountListItems.`n=================`n"


Remove-PSSnapin microsoft.sharepoint.powershell -ErrorAction SilentlyContinue